package com.example.androidstudy.dao.daoImp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.example.androidstudy.dao.PersonDao;
import com.example.androidstudy.model.Person;
import com.example.androidstudy.util.database.DbHelper;

import java.util.ArrayList;
import java.util.List;

public class PersonDaoImp implements PersonDao {

    DbHelper dbHelper = null;

    public PersonDaoImp(Context context) {
        this.dbHelper = new DbHelper(context,"person.db",null,1);
    }

    @Override
    public void add(Person p) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",p.getName());
        values.put("pwd",p.getPwd());
        db.insert("person",null,values);
        db.close();
    }

    @Override
    public void remove(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("person","id=?",new String[]{id+""});
        db.close();
    }

    @Override
    public void update(Person p) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",p.getName());
        values.put("pwd",p.getPwd());
        db.update("person",values,"id=?",new String[]{p.getId()+""});
        db.close();
    }

    @Override
    public Person findById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Person person = null;
        Cursor cursor = db.query("person",null,"id=?",new String[]{id+""},null,null,null);
        if(cursor.moveToNext()){
            person = new Person();
            person.setId(cursor.getInt(0));
            person.setName(cursor.getString(1));
            person.setPwd(cursor.getString(2));
        }
        db.close();
        return person;
    }

    @Override
    public List<Person> findAll() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<Person> list = new ArrayList<Person>();
        Person person = null;
        Cursor cursor = db.rawQuery("select * from person",null);
        while (cursor.moveToNext()){
            person = new Person();
            person.setId(cursor.getInt(0));
            person.setName(cursor.getString(1));
            person.setPwd(cursor.getString(2));
            list.add(person);
        }
        db.close();
        return list;
    }
}
